<?php
namespace app\index\controller;
use app\model\Ram as RamModel;
use app\model\UserToken as UserTokenModel;

use think\Db;


class Ram extends Base
{   
    protected $noCheckToken = ['login'];

    /**
     * 登录
     * @Author   cch
     * @DateTime 2020-05-29T12:06:40+0800
     * @param    $mobile   [description]
     * @param    $verify   验证码
     * @return             [description]
     */
    public function login(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        
        $fields = [
            'must'=>['account','password','user_id'],
            'nomust'=>[]
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            exception($params['error_msg'],400);
        }

        $model = new RamModel();
        $data = $model->where([
            ['user_id','=',$param['user_id']],
            ['account','=',$param['account']],
        ])->find();
        if ( empty($data) ) {
            return apiResult('5000','账号不存在');
        }
        if ( $data['password'] != md5($params['password']) ) {
            return apiResult('5000','密码错误');
        }

        Db::startTrans();
        try{
            // 生成token
            $token_data = [
                'user_id'=>$data['user_id'],
                'access_token'=>uuidCreate(),
                'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
                'utype'=>1,
                'ram_id'=>$data['id'],
            ];
            UserTokenModel::where('ram_id',$token_data['ram_id'])->delete();
            if ( !UserTokenModel::insert($token_data) ) {
                throw new \Exception("token生成失败");
            }

            // 记录最后登录时间
            $model->where('id',$data['id'])->update(['login_time'=>time()]);
            Db::commit();
            return apiResult('2000','登录成功',$token_data);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    // 列表
    public function index(){
        $ulogin = $this->login_user;
        $map_params = [
           
        ];
        $map = getSearchParam($map_params);

        $map[] = ['user_id','=',$ulogin['user_id']];
        $model = new RamModel();

        $list = $model->where($map)->order('id','desc')->select()->toarray();
        foreach ($list as $k => $vo) {
       
        }

        return apiResult('2000','获取成功',$list);
    }

    // 新增
    public function save(){
        $ulogin = $this->login_user;

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'must'=>['account','password'],
            'nomust'=>['truename','mobile','headimage','email']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }

        $model = new RamModel();
        // 启动事务 
        Db::startTrans();
        try{
            $save_data['password'] = md5($save_data['password']);
            $save_data['ctime'] = time();
            $save_data['user_id'] = $ulogin['user_id'];

            if ( $model->where([
                ['user_id','=',$save_data['user_id']],
                ['account','=',$save_data['account']],
            ])->count() > 0 ) {
                throw new \Exception("用户名已存在");
            }

            if ( !$model->insert($save_data) ) {
                throw new \Exception("保存失败");
            }

            // 更新成功 提交事务
            Db::commit();

            return apiResult('2000','提交成功',$save_data['uuid']);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    // 更新
    public function update(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        if ( empty($param['id']) ) {
            exception('id不能为空',400);
        }

        $fields = [
            'nomust'=>['password','truename','mobile','headimage','email']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }
        if (empty($save_data)) {
            return apiResult('5000','无任何修改');
        }

        if ( !empty($save_data['password']) ) {
            $save_data['password'] = md5($save_data['password']);
        }else{
            unset($save_data['password']);
        }

        $model = new RamModel();
        // 启动事务 
        Db::startTrans();
        try{
            if ( $model->where('id',$param['id'])->update($save_data) === false ) {
                throw new \Exception("保存失败");
            }
            // 更新成功 提交事务
            Db::commit();

            return apiResult('2000','更新成功');
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

   


}
